package cn.i5.remoteinvocationcontrol.core;

import cn.i5.remoteinvocationcontrol.config.RemoteInvocationControlConfig;
import cn.i5.remoteinvocationcontrol.constant.ControlWay;
import cn.i5.remoteinvocationcontrol.utils.CommonUtils;
import org.springframework.util.CollectionUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

/**
 * Ip白名单校验者
 *
 * @author mc0710
 */
public class WhiteIpChecker {

    /**
     * 校验
     */
    public void check(RemoteInvocationControlConfig remoteInvocationControlConfig) {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String ip = CommonUtils.getIp(request);
        Map<ControlWay, List<String>> controlWayMap = remoteInvocationControlConfig.getControlWayMap();
        if (!CollectionUtils.isEmpty(controlWayMap) && !controlWayMap.get(ControlWay.WHITE_IP).contains(ip)) {
            throw new RuntimeException("当前IP不能访问");
        }
    }
}
